<template>
	<view class="express-create-page">
		<!-- 内容区域 -->
		<view class="content">
			<!-- 发货地址 -->
			<view class="address-section">
				<view class="section-title">发货地址</view>
				<view class="address-card" @click="selectSenderAddress">
					<view class="address-info" v-if="senderAddress">
						<view class="address-name-row">
							<text class="name">{{ senderAddress.name }}</text>
							<text class="phone">{{ formatPhone(senderAddress.mobile) }}</text>
						</view>
						<view class="address-detail">
							{{ senderAddress.province }}{{ senderAddress.city }}{{ senderAddress.district }}{{ senderAddress.address }}
						</view>
					</view>
					<view class="address-placeholder" v-else>
						<text class="placeholder-text">请选择发货地址</text>
					</view>
					<uv-icon name="arrow-right" size="16" color="#C8C8C8"></uv-icon>
				</view>
			</view>

			<!-- 收货地址 -->
			<view class="address-section">
				<view class="section-title">收货地址</view>
				<view class="address-card" @click="selectReceiverAddress">
					<view class="address-info" v-if="receiverAddress">
						<view class="address-name-row">
							<text class="name">{{ receiverAddress.name }}</text>
							<text class="phone">{{ formatPhone(receiverAddress.mobile) }}</text>
						</view>
						<view class="address-detail">
							{{ receiverAddress.province }}{{ receiverAddress.city }}{{ receiverAddress.district }}{{ receiverAddress.address }}
						</view>
					</view>
					<view class="address-placeholder" v-else>
						<text class="placeholder-text">请选择收货地址</text>
					</view>
					<uv-icon name="arrow-right" size="16" color="#C8C8C8"></uv-icon>
				</view>
			</view>

			<!-- 物流公司选择 -->
			<view class="logistics-section">
				<view class="section-title">物流公司</view>
				<view class="logistics-options">
					<view class="logistics-option" :class="{ active: selectedLogistics.id === 'kuayue' }"
						@click="selectLogistics({ id: 'kuayue', name: '跨越物流' })">
						<uv-image src="/static/images/express/kuayue.png" width="40" height="40" radius="20"></uv-image>
						<text class="logistics-name">跨越物流</text>
						<uv-icon v-if="selectedLogistics.id === 'kuayue'" name="checkmark-circle-fill" size="20"
							color="#fe6600"></uv-icon>
					</view>
					
					<view class="logistics-option" :class="{ active: selectedLogistics.id === 'yimidida' }"
						@click="selectLogistics({ id: 'yimidida', name: '壹米滴答' })">
						<uv-image src="/static/images/express/yimidida.png" width="40" height="40"
							radius="20"></uv-image>
						<text class="logistics-name">壹米滴答</text>
						<uv-icon v-if="selectedLogistics.id === 'yimidida'" name="checkmark-circle-fill" size="20"
							color="#fe6600"></uv-icon>
					</view>
				</view>
			</view>

			<!-- 物品信息 -->
			<view class="goods-section">
				<view class="section-title">物品信息</view>
				<view class="goods-card" @click="showGoodsModal">
					<view class="goods-info" v-if="goodsInfo.name">
						<view class="goods-main">
							<text class="goods-name">{{ goodsInfo.name }}</text>
							<text class="goods-weight">{{ goodsInfo.weight }}KG</text>
						</view>
					</view>
					<view class="goods-placeholder" v-else>
						<text class="placeholder-text">请输入物品信息</text>
					</view>
					<uv-icon name="arrow-right" size="16" color="#C8C8C8"></uv-icon>
				</view>
			</view>

			<!-- 预估运费 -->
			<view class="goods-section">
				<view class="section-title">预估运费</view>
				<view class="goods-card" @click="openFreightPicker">
					<view class="goods-placeholder" v-if="freightText == ''">
						<text class="placeholder-text">请选择</text>
					</view>
					<view class="goods-info" v-else>
						<view class="goods-main">
							<text class="goods-name">{{ freightText }}</text>
						</view>
					</view>
					<uv-icon name="arrow-right" size="16" color="#C8C8C8"></uv-icon>
				</view>
				<uv-picker ref="freightPicker" :columns="freightColumns" @confirm="freightConfirm"
					keyName="name"></uv-picker>
			</view>

			<!-- 付款方式 -->
			<view class="payment-section">
				<view class="section-title">付款方式</view>
				<view class="payment-options">
					<!-- <view class="payment-option" :class="{ active: paymentMethod === 1 }"
						@click="selectPaymentMethod(1)">
						<text>寄付</text>
						<text class="desc">运费由寄件方支付</text>
					</view> -->
					<view class="payment-option" :class="{ active: paymentMethod === 2 }"
						@click="selectPaymentMethod(2)">
						<text>到付</text>
						<text class="desc">运费由收件方支付</text>
					</view>
				</view>
			</view>

			<!-- 预估费用 -->
			<view class="estimate-section" v-if="estimatePrice !== null">
				<view class="estimate-item">
					<text class="label">预估运费</text>
					<text class="price">¥{{ estimatePrice }}</text>
				</view>
			</view>

			<!-- 底部操作栏 -->
			<view class="bottom-bar">
				<uv-button class="order-btn" :disabled="!canSubmit" :custom-style="{
            backgroundColor: canSubmit ? '#fe6600' : '#E5E5E5',
            color: canSubmit ? '#FFFFFF' : '#999999',
            border: 'none',
            width: '100%',
            height: '44px',
            borderRadius: '4px',
            fontSize: '16px',
            fontWeight: 'bold'
          }" @click="submitOrder">
					下单
				</uv-button>
			</view>
		</view>

		<!-- 物品信息弹窗 -->
		<uv-popup ref="goodsPopup" mode="bottom" border-radius="10">
			<view class="goods-popup">
				<view class="popup-header">
					<text class="header-title">物品信息</text>
					<uv-icon name="close" size="20" @click="closeGoodsModal"></uv-icon>
				</view>

				<view class="popup-content">
					<view class="goods-input">
						<uv-input v-model="tempGoodsInfo.name" placeholder="请输入物品名称" border="bottom" clearable />
					</view>

					<view class="weight-control">
						<view class="weight-label">重量(kg)</view>
						<view class="weight-selector">
							<uv-button class="weight-btn minus" size="mini" :custom-style="{height:'30px'}"
								@click="decreaseWeight">
								-
							</uv-button>
							<input class="weight-input" v-model="tempGoodsInfo.weight" type="digit" />
							<uv-button class="weight-btn plus" size="mini" :custom-style="{height:'30px'}"
								@click="increaseWeight">
								+
							</uv-button>
						</view>
					</view>
				</view>

				<view class="popup-footer">
					<uv-button type="primary" @click="confirmGoodsInfo" :custom-style="{
              backgroundColor: '#fe6600',
              color: '#FFFFFF',
              border: 'none',
              height: '44px',
              borderRadius: '4px',
              fontSize: '16px'
            }">
						确定
					</uv-button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				statusBarHeight: 0,
				senderAddress: null,
				receiverAddress: null,
				goodsInfo: {
					name: '',
					weight: 1
				},
				tempGoodsInfo: {
					name: '',
					weight: 1
				},
				paymentMethod: 2, // 1: 寄付, 2: 到付
				selectedLogistics: {
					id: 'kuayue',
					name: '跨越物流'
				},
				estimatePrice: null, // 预估运费
				freightColumns: [],
				freightText: '',
				serviceMode: '',
			}
		},

		computed: {
			canSubmit() {
				return this.senderAddress && this.receiverAddress && this.goodsInfo.name
			}
		},
		watch: {
			// 监听关键数据变化，重新计算预估运费
			'senderAddress': 'calculateEstimatePrice',
			'receiverAddress': 'calculateEstimatePrice',
			'goodsInfo': {
				handler: 'calculateEstimatePrice',
				deep: true
			},
			'selectedLogistics': 'calculateEstimatePrice',
			'paymentMethod': 'calculateEstimatePrice'
		},

		onLoad(option) {
			let expressCode = option.expressCode

			if (expressCode == 'kuayue') {
				this.selectedLogistics = {
					id: expressCode,
					name: '跨越物流'
				}
			} else if (expressCode == 'yimidida') {
				this.selectedLogistics = {
					id: expressCode,
					name: '壹米滴答'
				}
			}

			// 获取状态栏高度，处理刘海屏
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
		},

		methods: {
			openFreightPicker() {
				this.$refs.freightPicker.open();
			},
			freightConfirm(e) {
				if (e.value.length > 0) {
					let value = e.value[0];
					this.freightText = value.name;
					this.serviceMode = value.id;
					return;
				}
				this.$wanlshop.msg('您的地址暂不支持该快递，请您选择其他快递方式！', 2500, true)
				return;
			},
			// 完善 loadData 方法
			async loadData(address_id, source) {
				try {
					await uni.request({
						url: '/wanlshop/user/getAddress',
						method: 'POST',
						data: {
							address_id: address_id
						},
						success: (res) => {
							if (source === 'sender') {
								this.senderAddress = res.data;
							} else if (source === 'receiver') {
								this.receiverAddress = res.data;
							}
						},
					});

				} catch (error) {
					console.error('获取地址信息失败:', error);
				}
			},
			goBack() {
				uni.navigateBack()
			},

			// 修改 selectSenderAddress 方法
			selectSenderAddress() {
				this.$wanlshop.to('/pages/user/address/address?source=sender');
			},

			// 修改 selectReceiverAddress 方法
			selectReceiverAddress() {
				this.$wanlshop.to('/pages/user/address/address?source=receiver');
			},

			// 选择物流公司
			selectLogistics(logistics) {
				this.selectedLogistics = logistics
			},

			// 手机号掩码处理
			formatPhone(phone) {
				if (!phone) return ''
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
			},

			// 显示物品信息弹窗
			showGoodsModal() {
				this.tempGoodsInfo = {
					...this.goodsInfo
				}
				this.$refs.goodsPopup.open()
			},

			// 关闭物品信息弹窗
			closeGoodsModal() {
				this.$refs.goodsPopup.close()
			},

			// 增加重量
			increaseWeight() {
				this.tempGoodsInfo.weight = parseFloat((parseFloat(this.tempGoodsInfo.weight) + 0.5).toFixed(1))
			},

			// 减少重量
			decreaseWeight() {
				if (this.tempGoodsInfo.weight > 0.5) {
					this.tempGoodsInfo.weight = parseFloat((parseFloat(this.tempGoodsInfo.weight) - 0.5).toFixed(1))
				}
			},

			// 确认物品信息
			confirmGoodsInfo() {
				this.goodsInfo = {
					...this.tempGoodsInfo
				}
				this.$refs.goodsPopup.close()
			},

			// 选择付款方式
			selectPaymentMethod(method) {
				this.paymentMethod = method
			},

			// 计算预估运费（模拟接口调用）
			async calculateEstimatePrice() {
				// 只有当所有必要信息都填写完成时才计算运费
				if (!this.senderAddress || !this.receiverAddress || !this.goodsInfo.name) {
					this.estimatePrice = null
					return
				}

				try {
					// 模拟异步请求获取预估运费
					await uni.request({
						url: '/wanlshop/express/getEstimatePrice',
						method: 'POST',
						data: {
							send_address_id: this.senderAddress.id,
							receipt_address_id: this.receiverAddress.id,
							name: this.goodsInfo.name,
							weight: this.goodsInfo.weight,
							express_id: this.selectedLogistics.id,
							pay_type: this.paymentMethod
						},
						success: (res) => {
							this.freightColumns = [res.data];
							if (res.data.length > 0) {
								let firstData = res.data[0];
								this.freightText = firstData.name;
								this.serviceMode = firstData.id;
							} else {
								this.freightText = '';
								this.serviceMode = 0;
							}
						}
					})
				} catch (error) {
					console.error('计算运费失败:', error)
					this.estimatePrice = null
				}
			},

			// 提交订单
			async submitOrder() {
				if (!this.canSubmit) return;

				uni.$uv.http.post('/wanlshop.express/createOrder', {
					send_address_id: this.senderAddress.id,
					receipt_address_id: this.receiverAddress.id,
					goods_name: this.goodsInfo.name,
					weight: this.goodsInfo.weight,
					express_name: this.selectedLogistics.id,
					pay_type: this.paymentMethod,
					service_mode: this.serviceMode,
				}).then(res => {
					if (res.res.code == 1) {
						this.$wanlshop.msg(res.res.msg, 2000, true);
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/express/list'
							});
						}, 2000);
						return;
					}
					this.$wanlshop.msg(res.res.msg, 3000, true, 'none');
				}).catch(error => {
					this.$wanlshop.msg('获取失败，请稍后重试', 2000, true)
				});
			}
		},

		// 修改 onShow 中的地址选择回调处理
		onShow() {
			const eventChannel = this.getOpenerEventChannel();
			if (eventChannel) {
				eventChannel.on('addressSelected', (data) => {
					if (data.source === 'sender') {
						// 如果返回的是完整地址对象
						if (data.address) {
							this.senderAddress = data.address;
						}
						// 如果只返回地址ID，则调用接口获取详情
						else if (data.address_id) {
							this.loadData(data.address_id, 'sender');
						}
					} else if (data.source === 'receiver') {
						// 如果返回的是完整地址对象
						if (data.address) {
							this.receiverAddress = data.address;
						}
						// 如果只返回地址ID，则调用接口获取详情
						else if (data.address_id) {
							this.loadData(data.address_id, 'receiver');
						}
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background: #F5F5F5;
	}
</style>

<style lang="scss" scoped>
	.express-create-page {
		min-height: 100vh;
		background-color: #F5F5F5;
	}

	.content {
		padding: 24rpx;
		margin-top: 20rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
		color: #333333;
		padding-left: 10rpx;
	}

	.address-card {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.address-info {
		flex: 1;
	}

	.address-name-row {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;

		.name {
			font-size: 32rpx;
			font-weight: bold;
			color: #333333;
		}

		.phone {
			font-size: 28rpx;
			color: #666666;
			padding-left: 20rpx;
		}
	}

	.address-detail {
		font-size: 28rpx;
		color: #666666;
		line-height: 1.4;
	}

	.address-placeholder {
		flex: 1;

		.placeholder-text {
			font-size: 30rpx;
			color: #999999;
		}
	}

	.logistics-options {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.logistics-option {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 2rpx solid #EEEEEE;

		&:last-child {
			border-bottom: none;
		}

		.logistics-name {
			flex: 1;
			font-size: 30rpx;
			margin-left: 20rpx;
			color: #333333;
		}
	}

	.goods-card {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.goods-info {
		flex: 1;
	}

	.goods-main {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.goods-name {
			font-size: 30rpx;
			color: #333333;
		}

		.goods-weight {
			font-size: 28rpx;
			color: #999999;
		}
	}

	.goods-placeholder {
		flex: 1;

		.placeholder-text {
			font-size: 30rpx;
			color: #999999;
		}
	}

	.payment-options {
		display: flex;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.payment-option {
		flex: 1;
		padding: 40rpx 20rpx;
		text-align: center;
		font-size: 30rpx;
		color: #666666;
		border-right: 2rpx solid #EEEEEE;
		display: flex;
		flex-direction: column;
		align-items: center;

		&:last-child {
			border-right: none;
		}

		&.active {
			color: #333333;
			background-color: #FAFAFA;
			font-weight: bold;

			.desc {
				font-size: 26rpx;
				color: #fe6600;
			}
		}

		.desc {
			font-size: 24rpx;
			margin-top: 10rpx;
			color: #999999;
		}
	}

	.estimate-section {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 140rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);

		.estimate-item {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.label {
				font-size: 30rpx;
				color: #333333;
			}

			.price {
				font-size: 36rpx;
				font-weight: bold;
				color: #fe6600;
			}
		}
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 136rpx;
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		padding: 24rpx;
		box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.1);
		z-index: 99;
	}

	.goods-popup {
		padding: 30rpx;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 40rpx;

			.header-title {
				font-size: 34rpx;
				font-weight: bold;
			}
		}

		.popup-content {
			min-height: 300rpx;

			.goods-input {
				margin-bottom: 40rpx;
			}

			.weight-control {

				.weight-label {
					font-size: 30rpx;
					color: #333333;
					margin-bottom: 30rpx;
				}

				.weight-selector {
					display: flex;
					align-items: center;

					.weight-btn {
						width: 60rpx;
						height: 60rpx;

						&.minus {
							background-color: #F5F5F5;
							border: 2rpx solid #DDDDDD;
						}

						&.plus {
							background-color: #fe6600;
							border: 2rpx solid #fe6600;
							color: #FFFFFF;
						}
					}
				}

				.weight-input {
					width: 120rpx;
					height: 60rpx;
					text-align: center;
					border: 2rpx solid #DDDDDD;
					border-left: none;
					border-right: none;
				}
			}
		}
	}

	.payment-section {
		padding-bottom: 200rpx;
	}

	.popup-footer {
		margin-top: 60rpx;
		text-align: center;
	}
</style>